const vscode = require('vscode');
const path = require('path');

function activate(context) { 
  let disposable = vscode.commands.registerCommand('csv-code-navigator.navigate', async () => {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
      return; // No open text editor
    }

    const document = editor.document;
    if (document.languageId !== 'csv') {
      vscode.window.showErrorMessage('This command is only available in CSV files.');
      return;
    }

    const line = editor.selection.active.line;
    const text = document.lineAt(line).text;

    // Split the CSV line into an array of values
    const values = text.split(',').map(s => s.trim().replace(/"/g, ''));

    // Extract relevant fields
    const [sha, filename, url, lines, title, comment, priority, category, additional, id, privateFlag] = values;

    if (!filename || !lines) {
      vscode.window.showErrorMessage('Invalid CSV format or missing required fields.');
      return;
    }

    // Parse line range
    const [startLineStr, endLineStr] = lines.split('-');
    const startLine = parseInt(startLineStr.split(':')[0]);
    const startColumn = parseInt(startLineStr.split(':')[1]) || 0;

    // Construct absolute file path
    const workspaceFolder = vscode.workspace.workspaceFolders[0];
    if (!workspaceFolder) {
      vscode.window.showErrorMessage('No workspace folder found.');
      return;
    }
    const filePath = path.join(workspaceFolder.uri.fsPath, filename);

    try {
      console.log('scode.workspace.fs.',vscode.workspace.fs);
      
      // Check if the file exists
      if (!await vscode.workspace.fs.stat(vscode.Uri.file(filePath))) {
        vscode.window.showErrorMessage(`File not found: ${filePath}`);
        return;
      }

      // Open the file and navigate to the specified position
      const doc = await vscode.workspace.openTextDocument(filePath);
      console.log('doc',doc);
      
      const targetEditor = await vscode.window.showTextDocument(doc);

      // Set the cursor to the specified line and column
      const position = new vscode.Position(startLine - 1, startColumn);
      targetEditor.selection = new vscode.Selection(position, position);
      targetEditor.revealRange(new vscode.Range(position, position));

      vscode.window.showInformationMessage(`Navigated to ${filePath}:${startLine}:${startColumn}`);
    } catch (error) {
      vscode.window.showErrorMessage(`Failed to navigate to code: ${error.message}`);
    }
  });

  context.subscriptions.push(disposable);
}

function deactivate() {}

module.exports = {
  activate,
  deactivate
};
//检查当前文件是否为CSV格式：如果当前编辑器中的文件不是CSV格式，则显示错误信息并退出。
//解析CSV行：从当前选中的行中提取文件路径和行号范围等信息。
//清理文件路径：去除多余的引号，并将相对路径转换为绝对路径。
//检查文件是否存在：确保目标文件存在于工作区中。
//打开文件并定位到指定位置：使用 vscode.workspace.openTextDocument 和 vscode.window.showTextDocument 打开文件，并使用 vscode.Position 和 vscode.Selection 设置光标位置。